import { login, getUserInfo, logout } from "@/api/user";
import { deepTree } from "@/utils";
import store2 from "store2";
import router from "@/router";
export default {
  namespaced: true,

  state: {
    isAdd : false,//用户是否已经动态添加过路由
    token: store2.get("token") || "", // 用户token
    info: store2.get("info"), // 用户信息
    menus : [], //用户当前有权限的菜单数据
    menus:store2.get('menus') || [],
    routes : store2.get('routes') || [],//用户有权限访问的地址
  },

  mutations: {
    setIsAdd(state,payload) {
      state.isAdd = payload
    },
    setToken(state, payload) {
      state.token = payload;
      // localStorage.setItem('token', payload)
      store2.set("token", payload);
    },
    setInfo(state, payload) {
      state.info = payload;
      // localStorage.setItem("info", JSON.stringify(payload));
      store2.set("info", payload);
    },
    setMenus(state,payload) {
      state.menus = payload;
      store2.set('menus',payload)
    },
    setRoutes(state,payload){
      state.routes = payload;
      store2.set('routes',payload);

    }
  },

  actions: {
    /**
     * 登录动作
     */
    async login({ commit }, payload) {
      const data = await login(payload);
      // 1. 将 data.token 写入 store
      commit("setToken", data.token);

      return data;
    },
    //登出动作

    async logout ({commit} , flag = true) {
      flag && (await  logout());

      //清理数据
      commit('setIsAdd',false)
      store2.clearAll()
      //跳转路由
      router.replace("/login")
    },
    /**
     * 获取个人信息动作
     */
    async getPerson({ commit }) {
      const data = await getUserInfo();
      //将个人信息填入store
      commit("setInfo", data.info);
      //过滤掉 type = 2得菜单按钮
      const list = data.menus.filter(item => item.type !== 2)
      commit('setMenus',deepTree(list));
      //过滤出type为一 的具有router字段的数据

      const routes = data.menus
      .filter((item) => item.type === 1)
      .map((item) => item.router);
        commit("setRoutes", routes);

        return data.menus.filter((item) => item.type === 1); 
    },
  },
};